//
//  WMEClubInformationViewController.m
//  everyDay_duiTang
//
//  Created by 恩叔 on 16/2/26.
//  Copyright © 2016年 enshu. All rights reserved.
//

#import "WMEClubInformationViewController.h"
#import <Masonry.h>
#import <AFNetworking.h>
#import "WMEClubInformationModel.h"
#import "WMEClubInformationTableViewCell.h"
#import "WMEUserViewController.h"
#import "WMEClubHeadView.h"
#import "WMEClubCommentsViewController.h"
#import "WMEClubInformationPhotoTableViewCell.h"
#import <MJRefresh.h>
#import "WMEClubNewsViewController.h"
#import "WMEUserViewController.h"

#pragma maek - 点击club 的详情页 从 clubViewController push 过来的
@interface WMEClubInformationViewController ()<UITableViewDataSource, UITableViewDelegate ,userAvatarPushDelegate ,pushClubNewsDelegate, userAvatarPhotoPushDelegate>
@property (nonatomic, retain)UITableView *tableView;/**<主视图*/
@property (nonatomic, copy)NSString *urlStr;/**<网络请求的str*/
@property (nonatomic, retain)NSMutableArray *clubDataArr;/**<数据数组*/
@property (nonatomic, assign)NSInteger count;/**<总个数*/
@property (nonatomic, retain)NSNumber *next_start;/**<下次请求开始位置*/
@property (nonatomic, retain)NSDictionary *dic;/**<*/
@end

@implementation WMEClubInformationViewController

- (void)dealloc
{
    [_interface release];
    [_headDic release];
    [_commentCount release];
    [_tableView release];
    [_urlStr release];
    [_clubDataArr release];
    [_next_start release];
    [_dic release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithRed:244/255.0 green:244/255.0 blue:244/255.0 alpha:1];
    self.navigationItem.title = @"club的详情";
//    [self dataHead];
    [self createView];
    
    [self data];
    if (self.commentCount.integerValue > 25) {
        [self loadingFunction];
    }
}
#pragma mark - 创建视图
- (void)createView
{
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    //隐藏分隔线
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //隐藏滚动轴
    _tableView.showsVerticalScrollIndicator = NO;
    CGFloat height = [WMEClubHeadView heightWithText:_headDic[@"content"] FontOfSize:13];
    //创建头部视图
    WMEClubHeadView *head = [[WMEClubHeadView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, height + 150)];
    if (![_headDic[@"tags"][0][@"name"] length]) {
        head.frame = CGRectMake(0, 0, WIDTH, height + 120);
        if (![_headDic[@"photos"][0][@"path"] length]) {
            head.frame = CGRectMake(0, 0, WIDTH, height + 120);
        }else{
            head.frame = CGRectMake(0, 0, WIDTH, height + 120 + 90);
        }
    }else {
        if (![_headDic[@"photos"][0][@"path"] length]) {
            head.frame = CGRectMake(0, 0, WIDTH, height + 150);
        }else{
            head.frame = CGRectMake(0, 0, WIDTH, height + 150 + 90);
        }
    }
    head.dic = _headDic;
    //点击 来着 ... push 到具体的club的协议
    head.delegate = self;
    _tableView.tableHeaderView = head;
    [head release];
    _tableView.backgroundColor = [UIColor colorWithRed:244/255.0 green:244/255.0 blue:244/255.0 alpha:1];
    [self.view addSubview:_tableView];
    __block __typeof(&*self)bs = self;
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bs.view.mas_left);
        make.right.equalTo(bs.view.mas_right);
        make.top.equalTo(bs.view.mas_top);
        make.bottom.equalTo(bs.view.mas_bottom);
    }];
    [_tableView release];
}
#pragma mark - 数据请求
- (void)data
{
    NSString *temp = @"http://203.80.144.212/napi/topic/comment/list/?platform_version=4.4.4&device_platform=L36h&__dtac=%257B%2522_r%2522%253A%2520%2522187455%2522%257D&screen_width=1080&screen_height=1776&__domain=www.duitang.com&app_version=67&start=0&platform_name=Android&locale=zh&app_code=nayutas&topic_id=126492";
    self.urlStr = [temp stringByReplacingOccurrencesOfString:@"topic_id=126492" withString:[NSString stringWithFormat:@"topic_id=%@", _interface]];
    AFHTTPSessionManager *data = [AFHTTPSessionManager manager];
    [data GET:_urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@", responseObject);
        NSArray *arr = responseObject[@"data"][@"object_list"];
        self.next_start = responseObject[@"data"][@"next_start"];
        _count += _next_start.integerValue;
        self.clubDataArr = [WMEClubInformationModel modelHandlerWithArray:arr];
        [_tableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        nil;
    }];
}

#pragma mark - tableView 的 协议方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _clubDataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (_clubDataArr.count != 0) {
        WMEClubInformationModel *model = _clubDataArr[indexPath.row];
        if (![model.path length]) {
            [_tableView registerClass:[WMEClubInformationTableViewCell class] forCellReuseIdentifier:@"clubInformation"];
            WMEClubInformationTableViewCell *clubInformationCell = [_tableView dequeueReusableCellWithIdentifier:@"clubInformation" forIndexPath:indexPath];
            clubInformationCell.model = model;
            //设置cell的背景色
            clubInformationCell.backgroundColor = [UIColor colorWithRed:244/255.0 green:244/255.0 blue:244/255.0 alpha:1];
            //设置cell隐藏分隔线
            clubInformationCell.selectionStyle = UITableViewCellSelectionStyleNone;
            //签点击用户头像跳转的协议
            clubInformationCell.delegate = self;
            return clubInformationCell;
        }else{
            [_tableView registerClass:[WMEClubInformationPhotoTableViewCell class] forCellReuseIdentifier:@"clubInformationPhoto"];
            WMEClubInformationPhotoTableViewCell *clubInformationPhoto = [_tableView dequeueReusableCellWithIdentifier:@"clubInformationPhoto" forIndexPath:indexPath];
            clubInformationPhoto.model = model;
            clubInformationPhoto.backgroundColor = [UIColor colorWithRed:244/255.0 green:244/255.0 blue:244/255.0 alpha:1];
            clubInformationPhoto.selectionStyle = UITableViewCellSelectionStyleNone;
            clubInformationPhoto.delegate = self;
            return clubInformationPhoto;
        }
    }else {
        return 0;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WMEClubInformationModel *model = _clubDataArr[indexPath.row];
    CGFloat h = [WMEClubInformationTableViewCell heightWithText:model.content FontOfSize:13];
    if (model.reply_count.integerValue != 0) {
        CGFloat height = [WMEClubInformationTableViewCell heightWithText:[NSString stringWithFormat:@"%@%@", model.repliesSenderName, model.repliesContent] FontOfSize:11];
        if (![model.path length]) {
            return h + height + 130;
        }else{
            return h + height + 130 + 100;
        }
    }else {
        if (![model.path length]) {
            return h + 90;
        }else {
            return h + 90 + 100;
        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    点击跳转评论详情页
    WMEClubInformationModel *model = _clubDataArr[indexPath.row];
    WMEClubCommentsViewController *comments = [[WMEClubCommentsViewController alloc] init];
    comments.model = model;
    [self.navigationController pushViewController:comments animated:YES];
}
#pragma mark -userAvatarPushDelegate 的协议方法
- (void)userAvatarPushAction:(NSString *)str userDic:(NSDictionary *)dictionary
{
    WMEUserViewController *userVC = [[WMEUserViewController alloc] init];
    UINavigationController *userNavi = [[UINavigationController alloc] initWithRootViewController:userVC];
    userVC.userId = str;
    userVC.userDic = dictionary;
    [self presentViewController:userNavi animated:YES completion:^{
    }];
    [userNavi release];
    [userVC release];
}
#pragma mark - userAvatarPhotoPushDelegate
- (void)userAvatarPhotoPushAction:(NSString *)str userDic:(NSDictionary *)dictionary
{
    WMEUserViewController *userVC = [[WMEUserViewController alloc] init];
    UINavigationController *userNavi = [[UINavigationController alloc] initWithRootViewController:userVC];
    userVC.userId = str;
    userVC.userDic = dictionary;
    [self presentViewController:userNavi animated:YES completion:^{
    }];
    [userNavi release];
    [userVC release];
}

#pragma mark -加载

- (void)loadingFunction
{
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
//    // 设置了底部inset
//    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 30, 0);
//    // 忽略掉底部inset
//    self.tableView.mj_footer.ignoredScrollViewContentInsetBottom = 30;
}
- (void)loadMoreData
{
    NSString *newUrlStr = [_urlStr stringByReplacingOccurrencesOfString:@"start=0" withString:[NSString stringWithFormat:@"start=%@", _next_start]];
    AFHTTPSessionManager *data = [AFHTTPSessionManager manager];
    [data GET:newUrlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@", responseObject);
        NSArray *arr = responseObject[@"data"][@"object_list"];
        self.next_start = responseObject[@"data"][@"next_start"];
        NSArray *tempArr = [WMEClubInformationModel modelHandlerWithArray:arr];
        [self.clubDataArr addObjectsFromArray:tempArr];
        [_tableView reloadData];
        if (_next_start.integerValue > self.commentCount.integerValue) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            [self.tableView.mj_footer endRefreshing];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        nil;
    }];

}
#pragma mark - 头部视图的协议方法
- (void)pushClubNewsAction:(NSDictionary *)dic
{
    WMEClubNewsViewController *clubNews = [[WMEClubNewsViewController alloc] init];
    clubNews.clubDic = dic;
    [self.navigationController pushViewController:clubNews animated:YES];
    [clubNews release];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)pushUserAction:(NSString *)str MyDic:(NSDictionary *)dic
{
    WMEUserViewController *userView = [[WMEUserViewController alloc] init];
    UINavigationController *userNavi = [[UINavigationController alloc] initWithRootViewController:userView];
    userView.userDic = dic;
    userView.userId = str;
    [self presentViewController:userNavi animated:YES completion:^{
    }];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
